# -*- coding: utf-8 -*-
# https://blog.csdn.net/weixin_52040868
# 公众号：测个der
# 微信：qing_an_an
import os
import aiofiles, asyncio
from datas import DataQueue
from PySide6.QtCore import QThread, Signal
from pyecharts import options as opts
from pyecharts.charts import Pie, Bar


class Worker(QThread):
    get_pie_signal = Signal(bytes)
    get_bar_signal = Signal(bytes)

    def __init__(self):
        super().__init__()

    def run(self):
        """Long-running task."""
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        data = DataQueue.get()
        tasks = asyncio.gather(self.read_html("bar_position.html", data),
                               self.read_html("pie_position.html", data))
        results = loop.run_until_complete(tasks)

        bar_result, pie_result = results
        self.get_pie_signal.emit(bar_result)
        self.get_bar_signal.emit(pie_result)


    async def products_bug(self, data):
        """bug统计"""
        value, bugs = ['未解决', '已关闭', '已修改'], [0, 0, 0]
        for data in data.products:
            bugs[0] += data.unResolved
            bugs[1] += data.closedBugs
            bugs[2] += data.fixedBugs
        return [list(z) for z in zip(value, bugs)]


    async def pie_datas(self, data):
        """饼状图数据"""
        products = await self.products_bug(data)
        await self.pie(products)


    async def bar_datas(self, data):
        """柱状图数据"""
        await self.bar(['未解决', '已关闭', '已修改'], data)


    async def read_html(self, files, data):
        """
        异步读取html
        """
        if not os.path.exists(files):
            await self.prepare_and_create_file(files, data)
        async with aiofiles.open(files, "rb") as f:
            contents = await f.read()
        return contents


    async def prepare_and_create_file(self, files, data):
        """
        准备数据并创建HTML文件
        """
        if files == "bar_position.html":
            await self.bar_datas(data)
        elif files == "pie_position.html":
            await self.pie_datas(data)
        else:
            print(f'No template for such file: {files}')

    async def pie(self, value: list):
        """饼状图"""
        c = (
            Pie(init_opts=opts.InitOpts(width='520px', height='330px'))
            .add(
                "BUG数据图",
                value,
                center=["50%", "50%"],
                radius=["30%", "60%"],
                itemstyle_opts=opts.ItemStyleOpts(
                    border_color='rgba(255, 255, 255, 255)',
                    border_width=2,
                    border_radius=10),
            )
            .set_global_opts(
                title_opts=opts.TitleOpts(title="BUG数据图"),
                legend_opts=opts.LegendOpts(pos_left="30%", ),
            )
            .set_series_opts(
                label_opts=opts.LabelOpts(formatter="{b}: {c}"
                                          ),
            )
            .render("pie_position.html")
        )

    async def bar(self, x_values, y_values):
        """柱状图"""
        name, unResolved, closedBugs, fixedBugs = [], [], [], []
        for values in y_values.products:
            name.append(values["name"])
            unResolved.append(values["unResolved"])
            closedBugs.append(values["closedBugs"])
            fixedBugs.append(values["fixedBugs"])
        c = (
            Bar(init_opts=opts.InitOpts(width='530px', height='340px'))
            .add_xaxis(name)
            .add_yaxis(x_values[0], unResolved, label_opts=opts.LabelOpts(position="top"))
            .add_yaxis(x_values[1], closedBugs, label_opts=opts.LabelOpts(position="top"))
            .add_yaxis(x_values[2], fixedBugs, label_opts=opts.LabelOpts(position="top"))
            .set_global_opts(
                xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-30)),
                title_opts={"text": "Bug数据", "subtext": "各项目情况"},
                legend_opts=opts.LegendOpts(pos_left="30%"),
            )
            .render("bar_position.html")
        )
